package top.bluesword.laboratory.aop;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 李林峰
 */
@Component
public class TestAdvisor extends StaticMethodMatcherPointcutAdvisor {

    public TestAdvisor() {
        super(new TestAdvice());
    }

    @Override
    public boolean matches(Method method, @NonNull Class<?> targetClass) {
        return method.isAnnotationPresent(TestAop.class) || targetClass.isAnnotationPresent(TestAop.class);
    }

    @Slf4j
    static class TestAdvice implements MethodInterceptor {

        @Override
        public Object invoke(@NonNull MethodInvocation invocation) throws Throwable {
            Object proceed;
            try {
                log.info("方法执行前通知");
                proceed = invocation.proceed();
                log.info("方法返回前通知");
            } catch (Exception e) {
                log.info("方法异常通知");
                throw e;
            } finally {
                log.info("方法执行后通知");
            }
            return proceed;
        }
    }

}
